package study;



import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.system.SystemUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author 刘伟涛
 * @Date 2023/12/12 14:09
 **/
@Slf4j
public class 获取网速 {
    public static void main(String[] args) {
        String str;
        while (true){
            Map<String, String> networkUpRate = getNetworkUpRate();
            Iterator<String> iterator = networkUpRate.keySet().iterator();
            System.out.println();
            while (iterator.hasNext()){
                String next = iterator.next();
                str = next.contains("DOWN")?"下载":"上传";
                System.out.println( str + networkUpRate.get(next));
            }
        }

    }

    public static Map<String, String> getNetworkUpRate() {
        Map<String, String> result = new HashMap<>();
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader input = null;
        try {
            boolean isWindows = SystemUtil.getOsInfo().isWindows();
            String command = isWindows ? "netstat -e" : "ifconfig";
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream(), Charset.forName("GBK")));
            long[] result1 = readInLine(input, isWindows);
            Thread.sleep(2 * 1000);
            pro.destroy();
            input.close();
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream(), Charset.forName("GBK")));
            long[] result2 = readInLine(input, isWindows);
            String downSpeed = FileUtil.readableFileSize(Convert.toLong(NumberUtil
                    .div(NumberUtil.sub(result2[0], result1[0]), 2)));
            String upSpeed = FileUtil.readableFileSize(Convert.toLong(NumberUtil
                    .div(NumberUtil.sub(result2[1], result1[1]), 2)));
            result.put("UP", upSpeed + (upSpeed.endsWith("B")?"/S":"B/S"));
            result.put("DOWN", downSpeed + (downSpeed.endsWith("B")?"/S":"B/S"));
        } catch (Exception e) {
            log.info(">>> 网络测速失败：", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.info(">>> 网络测速失败：", e);
                }
            }
            Optional.ofNullable(pro).ifPresent(Process::destroy);
        }
        return result;
    }

    private static long[] readInLine(BufferedReader input, boolean isWindows) {
        long[] arr = new long[2];
        StringTokenizer tokenStat;
        try {
            if (isWindows) {
                // 获取windows环境下的网口上下行速率
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                tokenStat = new StringTokenizer(input.readLine());

                System.out.println(tokenStat.nextToken());
                arr[0] = Long.parseLong(tokenStat.nextToken());
                arr[1] = Long.parseLong(tokenStat.nextToken());
            } else {
                // 获取linux环境下的网口上下行速率
                long rx = 0, tx = 0;
                String line = null;
                //RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
                //TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
                while ((line = input.readLine()) != null) {
                    if (line.contains("RX packets")) {
                        rx += Long.parseLong(line.substring(line.indexOf("RX packets") + 11, line.indexOf(" ",
                                line.indexOf("RX packets") + 11)));
                    } else if (line.contains("TX packets")) {
                        tx += Long.parseLong(line.substring(line.indexOf("TX packets") + 11, line.indexOf(" ",
                                line.indexOf("TX packets") + 11)));
                    }
                }
                arr[0] = rx;
                arr[1] = tx;
            }
        } catch (Exception e) {
            log.error(">>> 网络测速异常：", e);
        }
        return arr;
    }
}
